//
//  AddressListViewController.m
//  CenturyInterconnection
//
//  Created by Tian Wei You on 16/5/13.
//  Copyright © 2016年 Shanghai DuRui Information Technology Company. All rights reserved.
//

#import "AddressListViewController.h"
#import "AddressListTableViewCell.h"
#import "UpdateAddressControllerViewController.h"
#import "MGSwipeTableCell.h"

@interface AddressListViewController ()<UITableViewDelegate,UITableViewDataSource,UpdateAddressControllerViewControllerDelegate,MGSwipeTableCellDelegate>

@property(nonatomic,strong)UITableView*tableView;

@property(nonatomic,strong)NSMutableArray*allDatas;   //这个是 用到的array

#define AddressListCell @"AddressListTableViewCell"

@end

@implementation AddressListViewController

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, ACTUAL_HEIGHT(70), KScreenWidth, KScreenHeight-ACTUAL_HEIGHT(140)) style:UITableViewStyleGrouped];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    self.allDatas=[NSMutableArray array];
    
    [self makeNaviButton];
    [self getDatas];
    [self makeView];
    [self.tableView registerNib:[UINib nibWithNibName:AddressListCell bundle:nil] forCellReuseIdentifier:AddressListCell];
    [self.view addSubview:self.tableView];
}

-(void)getDatas{
    // http://viprunningonline.com/api/index.php?main_page=main_page=address_book
    NSString*urlStr=[NSString stringWithFormat:@"%@",HTTP_ADDRESS];
    NSDictionary*params=@{@"main_page":@"address_book",@"zenid":[UserSession instance].cookie};
    HttpManager *manager = [[HttpManager alloc]init];
    [manager getDataFromNetworkWithUrl:urlStr parameters:params compliation:^(id data, NSError *error) {
        NSLog(@"data>>>>>>>%@",data);
        NSString*number=[NSString stringWithFormat:@"%@",data[@"status"]];
        
        if ([number isEqualToString:@"1"]) {
            self.allDatas=data[@"data"];
        }
        
        [self.tableView reloadData];
    }];
}

-(void)makeNaviButton{
    
    self.title=@"ADDRESS LIST";
    
    UIButton *forkButton=[[UIButton alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(320), 0, ACTUAL_WIDTH(30), ACTUAL_HEIGHT(30))];
    [forkButton setImage:[UIImage imageNamed:@"nav_close"] forState:0];
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [leftButton setBackgroundImage:[UIImage imageNamed:@"nav_back"] forState:0];
    
    leftButton.frame=CGRectMake(0, 0, ACTUAL_WIDTH(23), ACTUAL_HEIGHT(23));
    //    forkButton.backgroundColor=[UIColor yellowColor];
    [forkButton addTarget:self action:@selector(comeBackToRoot) forControlEvents:UIControlEventTouchUpInside];
    [leftButton addTarget:self action:@selector(comeBack) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem*item1 = [[UIBarButtonItem alloc]initWithCustomView:forkButton];
    UIBarButtonItem*item= [[UIBarButtonItem alloc]initWithCustomView:leftButton];
    
    self.navigationItem.leftBarButtonItem=item;
    self.navigationItem.rightBarButtonItem=item1;
}

#pragma mark 返回事件
-(void)comeBackToRoot{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void)comeBack{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)makeView{
    self.view.backgroundColor=[UIColor whiteColor];
    
    UIButton*but1=[[UIButton alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(20), ACTUAL_HEIGHT(600), KScreenWidth-ACTUAL_WIDTH(40), ACTUAL_HEIGHT(50))];
    but1.backgroundColor=[UIColor blackColor];
    [but1 setTitle:@"Add a shipping address" forState:0];
    [but1 setTitleColor:[UIColor whiteColor] forState:0];
    [but1 addTarget:self action:@selector(gotoGetUpdateAddress) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:but1];
}

#pragma mark 设置Tabelview属性
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _allDatas.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 140;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    AddressListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:AddressListCell];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (self.allDatas.count==0) {}else{
        
        UILabel *label1=[cell viewWithTag:1];
        label1.text=self.allDatas[indexPath.row][@"firstname"];
        
        UILabel *label2=[cell viewWithTag:2];
        label2.text=self.allDatas[indexPath.row][@"lastname"];
        
        UILabel *label3=[cell viewWithTag:3];
        label3.text=self.allDatas[indexPath.row][@"street_address"];
        
        UILabel *label4=[cell viewWithTag:4];
        label4.text=self.allDatas[indexPath.row][@"city"];
        
        UILabel *label5=[cell viewWithTag:5];
        label5.text=self.allDatas[indexPath.row][@"postcode"];
        
        UILabel *label6=[cell viewWithTag:6];
        label6.text=self.allDatas[indexPath.row][@"state"];
        
        UILabel *label7=[cell viewWithTag:7];
        label7.text=self.allDatas[indexPath.row][@"country_name"];
        
        UILabel *label8=[cell viewWithTag:8];
        label8.text=self.allDatas[indexPath.row][@"telephone"];
        
    }
    cell.rightButtons = [self createRightButtons:1 withIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.rightSwipeSettings.transition = MGSwipeTransitionClipCenter;
    cell.delegate = self;
    return cell;
    
}

#pragma mark - 设置cell侧滑删除按钮
//- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
//    //删除
//
//    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"Delete" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//
//        // http://viprunningonline.com/api/index.php? main_page=address_book_process
//
//        NSDictionary*params=@{@"act":@"delete",@"address_book_id":self.allDatas[indexPath.row][@"address_book_id"]};
//
//        NSMutableString *urlStr=[NSMutableString stringWithFormat:@"%@main_page=address_book_process", HTTP_ADDRESS];
//
//        HttpManager *manager = [[HttpManager alloc]init];
//        [manager postDataFromNetworkWithUrl:urlStr parameters:params compliation:^(id data, NSError *error) {
//            NSString*number=[NSString stringWithFormat:@"%@",data[@"status"]];
//
//            if ([number isEqualToString:@"1"]) {
//                [JRToast showWithText:@"Delete the success！"];
//            }else{
//                [JRToast showWithText:data[@"status_message"]];
//            }
//        }];
//        //删除数据
//        [self getDatas];
//
//    }];
//    deleteAction.backgroundColor=[UIColor blackColor];
//    return @[deleteAction];
//}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

#pragma mark - MGSwipeTableCellDelegate
- (NSArray *)swipeTableCell:(MGSwipeTableCell *)cell
   swipeButtonsForDirection:(MGSwipeDirection)direction
              swipeSettings:(MGSwipeSettings *)swipeSettings
          expansionSettings:(MGSwipeExpansionSettings *)expansionSettings{
    
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    if (!indexPath) {
        return nil;
    }
    return [self createRightButtons:1 withIndexPath:indexPath];
    
}

- (BOOL) swipeTableCell:(MGSwipeTableCell *)cell
    tappedButtonAtIndex:(NSInteger)index
              direction:(MGSwipeDirection)direction
          fromExpansion:(BOOL)fromExpansion
{
    return NO;
}

- (NSArray *)createRightButtons:(int)count withIndexPath:(NSIndexPath *)indexPath{
    
    NSMutableArray *result = [NSMutableArray array];
    UIColor *colors[1] = {[UIColor blackColor]};
    NSString *titles[1] = {@"delete"};
    for (int i = 0; i < count; i++) {
        MGSwipeButton * button = [MGSwipeButton buttonWithTitle:titles[i]backgroundColor:colors[i] callback:^BOOL(MGSwipeTableCell * sender){
            
            //NSIndexPath *indexPath = [_tableView indexPathForCell:sender];
            if (!indexPath) {
                return NO;
            }
            if (i == 0)
            {
                NSDictionary*params=@{@"act":@"delete",@"address_book_id":self.allDatas[indexPath.row][@"address_book_id"]};
                
                NSMutableString *urlStr=[NSMutableString stringWithFormat:@"%@main_page=address_book_process", HTTP_ADDRESS];
                
                HttpManager *manager=[[HttpManager alloc]init];
                
                [manager postDataFromNetworkWithUrl:urlStr parameters:params compliation:^(id data, NSError *error) {
                    NSString*number=[NSString stringWithFormat:@"%@",data[@"status"]];
                    
                    if ([number isEqualToString:@"1"]) {
                        [JRToast showWithText:@"Delete the success！"];
                    }else{
                        [JRToast showWithText:data[@"status_message"]];
                    }
                }];
                //删除数据
                [self getDatas];
            }
            return YES;
        }];
        [result addObject:button];
    }
    return result;
    
}

#pragma mark 跳转添加地址界面
-(void)gotoGetUpdateAddress{
    UpdateAddressControllerViewController *vc=[[UpdateAddressControllerViewController alloc]init];\
    vc.delegate=self;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark 执行代理
-(void)delegateForBack{
    [self getDatas];
}

#pragma mark 点击选中返回数据
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic=@{@"lastName":self.allDatas[indexPath.row][@"lastname"],
                        @"postCode":self.allDatas[indexPath.row][@"postcode"],
                        @"streetAdress":self.allDatas[indexPath.row][@"street_address"],
                        @"addressID":self.allDatas[indexPath.row][@"address_book_id"]};
    if ([self.delegate respondsToSelector:@selector(delegateForBack:)]) {
        [self.delegate delegateForBack:dic];
    }
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
